﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;

namespace jQueryDotNetLib.Ajax
{
    public class jQueryAjax : IHttpHandler, System.Web.SessionState.IRequiresSessionState
    {

        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            string typeFull = context.Request["type"];
            string[] typeInfo = typeFull.Split(';');
            string type = typeInfo[0];
            string asm = typeInfo[1];
            string method = context.Request["method"];
            System.Reflection.Assembly asmO = System.Reflection.Assembly.Load(asm);
            if (asmO == null) throw new NotImplementedException("Could not load assembly:" + asm);


            //just in case they are passing in the aspx page type instead of the real type
            if (type.Contains("_aspx"))
            {
                type = type.Replace("ASP.", "");
                type = type.Replace("_aspx", "");
            }

            Type t = asmO.GetType(type, false, true);
            if (t == null) throw new NotImplementedException("Could not load type:" + type);
            

            System.Reflection.MethodInfo meth = t.GetMethod(method);
            if (meth == null) throw new NotImplementedException("Could not load method:" + method);

            //rnd:Math.random, data: dataVal, type:'" + ServerType + "', method:'" + MethodName + "'

            string uniqueID = context.Request["rnd"];
            string data = context.Request["data"];

            object result = meth.Invoke(null, new object[] { context, uniqueID , data});
            context.Response.Write(result.ToString());
        }

        #endregion
    }
}
